package com.metadata_system.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import com.metadata_system.common.dto.ApiResult;

import java.util.*;

@Slf4j
public class ApiSignUtils {
    public static String Salt = "wsdiyr2jle3gwyu7hcbk";
    public static Integer Md5Nums = 3;

    public static Map<String, Object> getConfig() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("key1", Salt);
        map.put("key2", Md5Nums);
        return map;
    }

    /**
     * 检查签名
     *
     * @param url
     * @param deviceId
     * @param timestamp
     * @param signParams
     * @param parameterMap
     * @return
     */
    public static ApiResult checkSign(String url, String deviceId, String timestamp, String signParams, Map<String, String[]> parameterMap) {
        long t1 = Long.valueOf(timestamp);
        long t2 = (new Date()).getTime();
        long diff = (t1 - t2);
        if (Math.abs(diff) > 100000) {
            System.out.println("========================= diff =========================");
            System.out.println(diff);
            return ApiResult.error("Api已经过期");
        }
        String str1 = "URL=" + url + ",DEVICEID=" + deviceId + ",TIMESTAMP=" + timestamp;
//        System.out.println("str1: "+str1);
        String str2 = "";
        List<String> str2List = new ArrayList<>();
        List<String> keyList = JSON.parseArray(JSON.toJSONString(parameterMap.keySet()), String.class);
        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for (String key : keyList) {
            str2List.add(key + "=" + parameterMap.get(key)[0]);
        }
        str2 = MyUtil.join(str2List, "&");
//        log.info("str2: "+str2);
        String str = str1 + "|" + str2 + "|" + Salt;

        System.out.println("签名前-str: "+str);
        for (int i = 0; i < Md5Nums; i++) {
            str = DigestUtils.md5DigestAsHex(str.getBytes());
        }
        System.out.println("签名后-str: "+str);
        if (str.equals(signParams)) {
            return ApiResult.success();
        }
        System.out.println("Api签名错误: 后端计算后=" + str + ",前端传递=" + signParams);
        return ApiResult.error("Api签名错误");
    }

    /**
     * 检查签名
     *
     * @param url
     * @param apikey
     * @param timestamp
     * @param signHeader
     * @param username
     * @param apiSecret
     * @param parameterMap
     * @return
     */
    public static ApiResult logicToolsCheckSign(String url, String apikey, String timestamp, String signHeader,String username, String apiSecret, Map<String, String[]> parameterMap) {
        long t1 = Long.valueOf(timestamp);
        long t2 = (new Date()).getTime();
        long diff = (t1 - t2);
        if (Math.abs(diff) > 100000) {
            return ApiResult.error("Api已经过期");
        }
        String str1 = "URL=" + url + "&APIKEY=" + apikey + "&USERNAME=" + username + "&TIMESTAMP=" + timestamp;
        log.info("str1: "+str1);

        String str2 = "";
        List<String> str2List = new ArrayList<>();
        List<String> keyList = JSON.parseArray(JSON.toJSONString(parameterMap.keySet()), String.class);
        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for (String key : keyList) {
            str2List.add(key + "=" + parameterMap.get(key)[0]);
        }
        str2 = MyUtil.join(str2List, "&");
        log.info("str2: "+str2);
        String str = str1 + "|" + str2 + "|" + apiSecret;

        log.info("str: "+str);
        String currSign=DigestUtils.md5DigestAsHex(str.getBytes());
        log.info("currSign: "+currSign);
        log.info("signHeader: "+signHeader);
        if (currSign.equals(signHeader)) {
            return ApiResult.success();
        }
        System.out.println("Api签名错误 " + (str1 + "|" + str2 + "|" + apiSecret) + "," + signHeader);
        return ApiResult.error("Api签名错误");
    }


    /**
     * 检查签名
     *
     * @param url
     * @param apikey
     * @param timestamp
     * @param signHeader
     * @param apiSecret
     * @param parameterMap
     * @return
     */
    public static ApiResult aiSystemCheckSign(String url, String apikey, String timestamp, String signHeader, String apiSecret, Map<String, String[]> parameterMap) {
        long t1 = Long.valueOf(timestamp);
        long t2 = (new Date()).getTime();
        long diff = (t1 - t2);
        if (Math.abs(diff) > 100000) {
            return ApiResult.error("Api已经过期");
        }
        String str1 = "URL=" + url + "&APIKEY=" + apikey + "&TIMESTAMP=" + timestamp;
        log.info("str1: "+str1);

        String str2 = "";
        List<String> str2List = new ArrayList<>();
        List<String> keyList = JSON.parseArray(JSON.toJSONString(parameterMap.keySet()), String.class);
        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for (String key : keyList) {
            str2List.add(key + "=" + parameterMap.get(key)[0]);
        }
        str2 = MyUtil.join(str2List, "&");
        log.info("str2: "+str2);
        String str = str1 + "|" + str2 + "|" + apiSecret;

        log.info("str: "+str);
        String currSign=DigestUtils.md5DigestAsHex(str.getBytes());
        log.info("currSign: "+currSign);
        log.info("signHeader: "+signHeader);
        if (currSign.equals(signHeader)) {
            return ApiResult.success();
        }
        System.out.println("Api签名错误 " + (str1 + "|" + str2 + "|" + apiSecret) + "," + signHeader);
        return ApiResult.error("Api签名错误");
    }


    public static String getSign(String url, String apikey, String timestamp, String apiSecret, Map<String, String[]> parameterMap) {
        String str1 = "URL=" + url + "&APIKEY=" + apikey + "&TIMESTAMP=" + timestamp;
        log.info("str1: " + str1);

        // URL=${ApiUrl}&APIKEY=${header.ApiKey}&TIMESTAMP=${header.Timestamp}
        String str2 = "";
        List<String> str2List = new ArrayList<>();
        List<String> keyList = JSON.parseArray(JSON.toJSONString(parameterMap.keySet()), String.class);
        keyList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });

        for (String key : keyList) {
            str2List.add(key + "=" + parameterMap.get(key)[0]);
        }
        str2 = MyUtil.join(str2List, "&");
        log.info("str2: " + str2);
        String str = str1 + "|" + str2 + "|" + apiSecret;
        log.info("str: "+str);
        String currSign=DigestUtils.md5DigestAsHex(str.getBytes());
        log.info("currSign: "+currSign);
        return currSign;
    }





    public static String test(Map<String, String[]> parameterMap, String url, String apikey, String apiSecret) {
        String timestamp = String.valueOf((new Date()).getTime()/1000L);

        String sign = getSign(url, apikey, timestamp, apiSecret, parameterMap);
        return JSON.toJSONString(parameterMap);
    }

    public static void main(String[] args) {
        Map<String, String[]> parameterMap=new HashMap<>();

        parameterMap.put("name", new String[]{"战斗机"});
        parameterMap.put("page", new String[]{"1"});
        parameterMap.put("pageSize", new String[]{"20"});

        String url="/api/ai-server/v001/Metadata/getList";
        String apikey="H7BHp5YQnGpZzrBzNhMba1a4Bf7B95ct";
        String apiSecret="adwQGC0wwTfNsGP6ifSder3HtHXWnQ5Z";
        String test = ApiSignUtils.test(parameterMap, url, apikey, apiSecret);


        System.out.println("test: "+test);
    }

}
